<?php


namespace app\shop\controller\admin;


use app\BaseController;
use app\enterprise\model\File as FileModel;
use app\enterprise\model\Message;
use app\enterprise\model\User;
use app\manage\model\Config;
use app\services\utils\Oss;
use app\shop\service\until\FileService;
use think\facade\App;
use think\facade\Filesystem;
use think\facade\Request;
use think\File;

class ImageController extends BaseController
{
    protected $disk = '';
    protected $url = '';

    public function __construct()
    {
        parent::__construct(app());
        $this->disk = env('filesystem.driver', 'local');
        $this->url = getDiskUrl() . '/';

    }

    /**
     * 上传图片到本地
     * @return \think\response\Json
     */
    public function uploadImage()
    {
        try {
            $userId = $this->request->middleware('userId');
            $file = $this->request->file('image');
            $fileService = new FileService();
            $info = $fileService->upload($userId, [], $file);
            return json([
                "errno" => 0,
                "data" => [
                    'url' => FileService::getFullUrl($info['src']) ,
                ]
            ]);
        } catch (\Exception $exception) {
            return json([
                "errno" => 1,
                "message" => $exception->getMessage()
            ]);
        }
    }

    // 上传一般文件
    public function uploadFile()
    {
        try {
            $userId = $this->request->middleware('userId');
            $file = $this->request->file('file');
            if(!$file){
                $file = $this->request->file('image');
            }
            $fileService = new FileService();
            $info = $fileService->upload($userId, [], $file);
            return $this->success([
                'src' => $info['src'],
                'url' => FileService::getFullUrl($info['src']),
                'ext' => $info['ext'],
                'file_id' => $info['file_id'],
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 头像
     * @return \think\response\Json
     */
    public function upload()
    {
        try {
            $userId = $this->request->middleware('userId');
            $file = $this->request->file('file');
            if(!$file){
                $file = $this->request->file('image');
            }
            $fileService = new FileService();
            $info = $fileService->upload($userId, [], $file,'avatar/' . $userId . '/');
            return $this->success([
                'src' => FileService::getFullUrl($info['src']),
                'path' => $info['src'],
                'ext' => $info['ext'],
                'file_id' => $info['file_id'],
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}